#!/usr/bin/env python

import copy
import os
import optparse
import sys
import subprocess
import tempfile

from charmicat import BadCommandLineError
import batchcat

from ypipi.slurm import BASFSlurmScript

def main():
    '''
    ypipi_batch_basf.py [opts] BASF_module_name input_files.txt

    Submits one job running `module_name' per line in `input_files.txt' using `sbatch'.
    '''
    
    op = optparse.OptionParser(usage=main.__doc__)
    

    op.add_option("-b", "--basf", dest='basf_path', default=None,
                  help='Use BASF script at PATH in job script',
                  metavar='PATH')
    op.add_option('-m', '--module-path', dest='module_path', default=None,
                  help='Add PATH to the LD_LIBRARY_PATH for the job',
                  metavar='PATH')
    op.add_option("-p", "--parameter", dest='basf_pars', action='append', default=[],
                  help='Push parameter NAME=VALUE to BASF script', metavar='NAME=VALUE')                  
    op.add_option("-s", "--stage", action='store_true', dest='stage', default=False,
                  help='Stage job output on local disk')
    
    batchcat.add_options(op)

    opts, args = op.parse_args()

    if len(args) == 0:
        msg = "Please supply the BASF module name and at least one input file."
        raise BadCommandLineError(msg, -1)

    module_name = args.pop(0)

    if len(args) == 0:
        msg = "Please supply a text file containing paths to input files, one path per line."
        raise BadCommandLineError(msg, -2)

    basf_pars = {}
    if len(opts.basf_pars) > 0:
        for p in opts.basf_pars:
            try:
                name, value = p.split('=')
            except ValueError:
                msg = "Parameter `{0}' supplied via `-p' option is not in format NAME=VALUE"
                raise BadCommandLineError(msg.format(p), -3)
            
            basf_pars[name] = value

    opts.basf_pars = basf_pars
            
    input_files = [line.strip() for line in open(args[0])]
    
    for path in input_files:
        scrobj = BASFSlurmScript(os.path.basename(path), module_name, path, copy.deepcopy(opts))
        batchcat.resource_managers['olympus'].add_script(scrobj)
        
    if opts.bcat_write is not None:
        batchcat.resource_managers['olympus'].write(path=opts.bcat_write)
    else:
        batchcat.resource_managers['olympus'].submit()

    return 0



if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
